﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CommonEngine.Helper
{
    /// <summary>
    /// API访问（携带用户密码）帮助器
    /// </summary>
    public sealed class NetHelper
    {
        /// <summary>
        /// 异步访问Url---绑定请求头部授权的用户及密码
        /// </summary>
        public static async Task<HttpResponseMessage> GetHttpClientResult(string Url, string username, string password)
        {
            var client = new HttpClient();
            var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password));
            //---将用户名和密码，绑定授权---
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            //---访问代理服务地址，并取到返回值---
            HttpResponseMessage response = await client.GetAsync(Url);
            return response;
        }

        /// <summary>
        /// 异步输出Api的请求结果
        /// </summary>
        public static async Task<string> GetApiResult(string apiUrl, string username, string password)
        {
            var response = await GetHttpClientResult(apiUrl, username, password);
            var rm = response.EnsureSuccessStatusCode();
            if (rm.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }
            else
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                return "HttpError: " + responseBody;  //请求失败的数据也可以一起返回的
            }
        }

    }
}
